﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;

#if UNITY_EDITOR
namespace Utility.Inspector
{
	public struct ContainerScope : IDisposable
	{
		string key;
		bool showContent;
		public bool ShowContent { get { return showContent; } }

		bool Open
		{
			get { return string.IsNullOrEmpty (key) ? true : EditorToolUtility.GetBool (key, true); }
			set
			{
				if (!string.IsNullOrEmpty (key))
				{
					EditorToolUtility.SetBool (key, value);
				}
			}
		}

		public void SetOpen (bool open)
		{
			Open = open;
		}

		static GUIStyle contentScopeStyle = new GUIStyle ()
		{
			padding = new RectOffset (3, 3, 5, 5),
			margin = new RectOffset (1, 1, -4, 0),
		};

		static GUIStyle titleStyle = new GUIStyle (GUI.skin.button)
		{
			alignment = TextAnchor.MiddleLeft,
			fontStyle = FontStyle.Bold
		};

		public static ContainerScope New (string key, GUIContent title)
		{
			var scope = new ContainerScope () { key = key };
			scope.showContent = scope.Open;
			title.text = (scope.showContent ? "\u25BC" : "\u25B6") + title.text;

			//total area
			var rect_full = EditorGUILayout.BeginVertical ();
			//title
			Rect rect_Title = GUILayoutUtility.GetRect (100, 20);
			//title button
			if (GUI.Button (rect_Title, title, titleStyle) && Event.current.button == 0)
			{
				scope.Open = !scope.showContent;
			}
			GUI.backgroundColor = Color.white;

			//content area
			Rect rect_content = EditorGUILayout.BeginVertical (scope.showContent ? contentScopeStyle : GUIStyle.none);
			if (scope.ShowContent)
			{
				GUI.Box (rect_content, "");
			}
			return scope;
		}

		public static ContainerScope New (string key)
		{
			return New (key, new GUIContent (key));
		}

		public static ContainerScope New (string key, string title)
		{
			return New (key, new GUIContent (title));
		}

		void IDisposable.Dispose ()
		{
			EditorGUILayout.EndVertical ();
			EditorGUILayout.EndVertical ();
		}
	}


}
#endif